#include <iostream>

#include <gtest/gtest.h>

#include "melon/client/thrift_client_pool.h"
#include "MessageExchangeService.h"
#include "im/adapters/message_exchange_adapter.h"

using imserver::MessageExchangeServiceClient;
using melon::client::ClientPool;

using namespace imserver;

void * ThreadFun(void * data) {
  ClientPool<MessageExchangeServiceClient> * pool = (ClientPool<MessageExchangeServiceClient>*)data;
  
  // const char * addrs[] = {"127.0.0.1:9091", "127.0.0.1:9093"};
  // const char * addrs[] = {"127.0.0.1:9199"};
  const char * addrs[] = {"10.16.15.197:9191"};
  int addr_count = sizeof(addrs) / sizeof(char*);

  MessageExchangeServiceClient * p = NULL;
  
  ImMessage im_msg;
  im_msg.seq_id = 0;
  im_msg.flags = 0;
  im_msg.sender = 288297970; // time(NULL);
  im_msg.receiver = 127646892; // time(NULL);
  im_msg.timestamp = time(NULL);
  im_msg.body = "message_exchange_test body";

  // for (int i = 0; i < 1000; ++i) {
  for (int i = 0; i < 10000; ++i) {
    std::cout << "GetMessageExchangeList " << i << std::endl;
    std::string addr(addrs[i % addr_count]);
    p = pool->Alloc(addr);
    if (!p) {
      continue;
    }
    bool success = true;
    try {
      p->CreateMessage(im_msg);
      std::cout << "AddMessageExchange " << i << std::endl;
      usleep(100);
    } catch (const std::exception & e) {
      std::cout << addr << " error:" << e.what() << std::endl;
      success = false;
    }
    pool->Release(addr, p, success);
  }
  return NULL;
}

const int kThreadCount = 27;

int main() {
  LOG_INIT("./test.log", "DEBUG");
  ClientPool<MessageExchangeServiceClient> pool;

  pthread_t ts[kThreadCount];

  for (int i = 0; i < kThreadCount; ++i) {
    pthread_create(&ts[i], NULL, ThreadFun, &pool);
  }

  for (int i = 0; i < kThreadCount; ++i) {
    pthread_join(ts[i], NULL);
  }
  return 0;
}

